<template>
  <el-form ref="ipRuleForm" :class="{ '': formDataIsValid }" :rules="rules" :model="ipInfo" :label-position="showMobilePage?'left':'right'" label-width="110px" class="lineHeight32">
    <el-row class="response-el-row">
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item label="IP封面" prop="cover" class="surface-plot-upload" style="margin-bottom:0;">
          <surface-plot-upload :cover="ipInfo.cover" @update:cover="coverUploadSuccess" />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item label="表情包范围" prop="range">
          <el-select :value="ipInfo.range" popper-class="global-select-down" name="range" @change="rangeChange">
            <el-option label="请选择" value="" />
            <el-option
              v-for="item in mengliEmojiRange"
              :key="item.type"
              :label="item.name"
              :value="item.type"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item label="IP名称" prop="ipName">
          <el-input
            :value="ipInfo.ipName"
            :maxlength="20"
            placeholder="请输入IP名称"
            name="name"
            type="text"
            @input="ipNameChange"
          />
        </el-form-item>
      </el-col>
      <el-col v-if="isShowDisableInput" :span="12" class="responsive-col-lg-8">
        <el-form-item label="表情数量" prop="workNum">
          <el-input
            :value="ipInfo.workNum"
            :disabled="true"
            placeholder=""
            name="workNum"
            type="text"
          />
        </el-form-item>
      </el-col>
      <template v-if="isShowDisableInput">
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="总下载量" prop="downloadNum">
            <el-input
              :value="ipInfo.downloadNum"
              :disabled="true"
              placeholder=""
              name="downloadNum"
              type="text"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="总发送量" prop="sendNum">
            <el-input
              :value="ipInfo.sendNum"
              :disabled="true"
              placeholder=""
              name="sendNum"
              type="text"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="总赞赏金额(元)" prop="rewardPrice">
            <el-input
              :value="ipInfo.rewardPrice"
              :disabled="true"
              placeholder=""
              name="rewardPrice"
              type="text"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="总赞赏次数" prop="rewardNum">
            <el-input
              :value="ipInfo.rewardNum"
              :disabled="true"
              placeholder=""
              name="rewardNum"
              type="text"
            />
          </el-form-item>
        </el-col>
      </template>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item label="已关联表情包" prop="relevantIds">
          <relate-emoji :ids="ids" :options="ipInfo.relevantIds" @postMessage="postMessage" />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item label="所属系列" prop="ipSeriesId">
          <ip-series-load ref="ipSeriesId" :options="{id:ipInfo.ipSeriesId, name:ipInfo.ipSeriesName}" style-set="width:240px;" @ipSeriesChange="ipSeriesChange" />
        </el-form-item>
      </el-col>
    </el-row>
    <div v-if="isIpImage">
      <Title font-size="16px" title="供应商信息" style="margin:8px 0 16px" />
      <el-row class="response-el-row">
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="供应商名称" prop="supplierId">
            <el-select
              v-loadmore="supplierLoadMore"
              :value="ipInfo.supplierId"
              :filter-method="supplierFilterData"
              popper-class="global-select-down"
              filterable
              size="small"
              placeholder="请搜索选择供应商"
              class="user-select filterableSelect remoteRequest1"
              @change="dataSelectChange($event, 'supplierId')">
              <el-option
                v-for="item in filterSuppliers"
                :key="item.id"
                :label="`${item.supplier}`"
                :value="item.id"/>
              <div v-if="supplierLoading" class="loading-container"><i class="el-icon-loading"/></div>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="商务订单分成" prop="accreditCost">
            <el-input
              :value="ipInfo.accreditCost"
              placeholder="请输入0-100数字"
              name="accreditCost"
              type="text"
              @input="rangeNumberChange($event, 'accreditCost')"
            >
              <span slot="suffix">%</span>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="电商销售分成" prop="ecomSaleCost">
            <el-input
              :value="ipInfo.ecomSaleCost"
              placeholder="请输入0-100数字"
              name="ecomSaleCost"
              type="text"
              @input="rangeNumberChange($event, 'ecomSaleCost')"
            >
              <span slot="suffix">%</span>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </div>
  </el-form>
</template>
<script>
import SurfacePlotUpload from '@/components/Mengli/surfacePlotUpload.vue';
import { mengliEmojiRange } from '@/utils/typeCfg';
import RelateEmoji from '@/components/RelateEmoji';
import IpSeriesLoad from '@/components/IpSeriesLoad';
import Title from '@/components/Title';
import { getSuppliers } from '@/api/mengli';
import { regNumberMax } from '@/utils/numFormat';
import { mapState } from 'vuex';

export default {
  name: 'IpInfoEdit',
  components: {
    SurfacePlotUpload,
    RelateEmoji,
    IpSeriesLoad,
    Title
  },
  props: {
    ipInfo: {
      type: Object,
      default: () => {
        return {
          ipName: '',
          range: '',
          cover: '',
          relevantIds: [],
          supplierId: '',
          accreditCost: '',
          ecomSaleCost: ''
        };
      }
    },
    isCloumn: {
      type: Boolean,
      default: false
    },
    isShowDisableInput: {
      type: Boolean,
      default: false
    },
    relevantList: {
      type: Object,
      default: () => {
        return {};
      }
    },
    isIpImage: {
      type: Boolean,
      default: () => {
        return false;
      }
    },
    defaultParams: {
      type: Object,
      default: () => {
        return {
          supplier: ''
        };
      }
    }
  },
  data() {
    return {
      mengliEmojiRange,
      supplierList: {
        item: [],
        page: 1,
        perPage: 20,
        total: ''
      },
      supplierLoading: false
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    formDataIsValid() {
      let isValid = true;
      if (this.$refs.ipRuleForm) {
        const { fields } = this.$refs.ipRuleForm;
        isValid = !fields.some(item => item.validateState === 'error');
      }
      let result;
      if (this.isIpImage) {
        const { ipInfo: { ipName, range, supplierId, accreditCost, ecomSaleCost }} = this;
        result = !!(ipName && range && (ecomSaleCost || ecomSaleCost === 0) && supplierId && (accreditCost || accreditCost === 0) && isValid);
      } else {
        const { ipInfo: { ipName, range }} = this;
        result = !!(ipName && range && isValid);
      }
      this.$emit('update:formValid', result);
      return result;
    },
    ids() {
      const ids = this.ipInfo.relevantIds.map(res => {
        return res.id;
      });
      return ids;
    },
    rules() {
      if (this.isIpImage) {
        return {
          'ipName': [
            { required: true, message: '请输入IP名称', trigger: ['change', 'blur'] },
            { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: ['change', 'blur'] }
          ],
          'range': [
            { required: true, message: '请选择表情包范围', trigger: ['change'] }
          ],
          'cover': [
            { required: true, message: '请上传IP封面图片', trigger: ['change', 'blur'] }
          ],
          'supplierId': [
            { required: true, message: '请选择供应商', trigger: ['change'] }
          ],
          'accreditCost': [
            { required: true, message: '请输入商务订单分成', trigger: ['change'] }
          ],
          'ecomSaleCost': [
            { required: true, message: '请输入电商销售分成', trigger: ['change'] }
          ]
        };
      } else {
        return {
          'ipName': [
            { required: true, message: '请输入IP名称', trigger: ['change', 'blur'] },
            { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: ['change', 'blur'] }
          ],
          'range': [
            { required: true, message: '请选择表情包范围', trigger: ['change'] }
          ],
          'cover': [
            { required: true, message: '请上传IP封面图片', trigger: ['change', 'blur'] }
          ]
        };
      }
    },
    filterSuppliers() {
      if (this.defaultParams.supplier) {
        const temp = [this.defaultParams.supplier];
        if (this.supplierList.items) {
          this.supplierList.items.forEach(item => {
            if (item.id !== this.defaultParams.supplier.id) {
              temp.push(item);
            }
          });
        }
        return temp;
      }
      return this.supplierList.items;
    }
  },
  created() {
    if (this.isIpImage) {
      this.getSupplierMethods(1, '');
    }
  },
  methods: {
    supplierFilterData(val) {
      this.getSupplierMethods(1, val);
    },
    supplierLoadMore() {
      const supplierList = this.filterSuppliers;
      const supplierObj = this.supplierList;
      const currentPage = supplierObj.page;
      const isMax = supplierList.length >= supplierObj.total;
      if (!isMax && !this.supplierLoading) {
        this.getSupplierMethods(currentPage + 1);
      }
    },
    // 获取供应商列表
    getSupplierMethods(page, name = '') {
      const params = {
        keyword: name
      };
      this.supplierLoading = true;
      getSuppliers(page, 10, params).then(({ data }) => {
        this.supplierLoading = false;
        if (page > 1 && this.supplierList.items) {
          const concatList = this.supplierList.items.concat(data.items);
          data.items = concatList;
          this.supplierList = data;
        } else {
          this.supplierList = data;
        }
      }).catch(e => {
        this.supplierLoading = false;
        console.error(e);
      });
    },
    // 用于手动触发表单验证
    triggerFormValidate() {
      this.$refs.ipRuleForm.validate();
    },
    clearValidate() {
      this.$refs.ipRuleForm.clearValidate();
    },
    ipNameChange(text) {
      const ipInfo = { ...this.ipInfo };
      ipInfo.ipName = text;
      this.$emit('update:ipInfo', ipInfo);
    },
    rangeChange(type) {
      const ipInfo = { ...this.ipInfo };
      ipInfo.range = type;
      this.$emit('update:ipInfo', ipInfo);
    },
    ipSeriesChange(data) { // ip系列修改
      const ipInfo = { ...this.ipInfo };
      this.$emit('update:ipInfo', { ...ipInfo, ipSeriesId: data.id });
    },
    // 图片上传成功
    coverUploadSuccess(url) {
      const ipInfo = { ...this.ipInfo };
      ipInfo.cover = url;
      this.$emit('update:ipInfo', ipInfo);
    },
    filterData(val) {
      this.$emit('getRelevantName', val);
    },
    postMessage(data) {
      const ipInfo = { ...this.ipInfo };
      ipInfo.relevantIds = data.relatedEmojiOptions;
      this.$emit('update:ipInfo', ipInfo);
    },
    dataSelectChange(val, filed) {
      const ipInfo = { ...this.ipInfo };
      ipInfo[filed] = val;
      this.$emit('update:ipInfo', ipInfo);
    },
    // 0-100的数字
    rangeNumberChange(value, filed) {
      const str = regNumberMax(value, 100);
      const ipInfo = { ...this.ipInfo };
      ipInfo[filed] = str;
      this.$emit('update:ipInfo', ipInfo);
    }
  }
};
</script>
<style lang="scss" scoped>
.response-el-row {
  &::v-deep {
    .el-form-item {
      margin-bottom: 24px;
      .el-form-item__content .el-input {
        font-size: 14px;
      }
    }
  }
}
.loading-container {
  width: 100%;
  text-align: center;
  i {
    color: #999;
  }
}
</style>
